package io.github.smileinmotion.oplog.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * sping 容器工具
 *
 * @author Mr.spc
 * @date 2022/2/25 18:08
 */
public class AppContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return AppContextUtil.applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AppContextUtil.applicationContext = applicationContext;
    }

    /**
     * 根据 对应的 Class 获取容器的bean
     *
     * @param clazz
     * @param <T>
     * @return T
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 根据 名称以及 对应的 Class 获取容器的bean
     *
     * @param beanName
     * @param <T>
     * @return T
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        return applicationContext.getBean(beanName, clazz);
    }

}
